import { useEffect, useState } from "react";
import cookies from "../utils/cookies";
import axios from "../utils/axios";
import qs from "qs";

function useAxios(method: string, url: string, params: any) {
    const host = "http://localhost:8080"
    const [data, setData] = useState<any>(null);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<any>(null);

    const fetchData = async () => {
        try {
            setIsLoading(true);
            setError(null);
            if (method === "get") {
                const query = qs.stringify(params);
                axios.get(url + "?" + query)
                    .then(res => {
                        //这里的res已经是 响应体中的数据 已经在 响应拦截器里被处理过了
                       if (res.code === 2002) {
                           setData(res.data);
                           setIsLoading(false);
                       }else {
                           console.log("错误消息"+res.data.message);
                        }
                    }).catch(err => {
                        alert(err.response.data.message)
                        setError(err.response.data.message);
                        setData(null);
                        setIsLoading(false);
                    });
            } else if (method === "post") {

                axios.post(url, JSON.stringify(params))
                    .then(res => {
                        console.log("res是：",res);
                        if (res.code === 2002) {
                            setData(res.data);
                            setIsLoading(false);
                            if (url === "/login") {
                                //设置cookie
                                cookies.set("token", res.data.token, 7);
                            }else if (url === "/logout") {
                                //删除cookie
                                cookies.remove("token");
                            }
                        }else {
                            console.log("错误消息"+res.data.message);
                        }
                    }).catch(err => {
                        alert(err.response.data.message)
                        setError(err.response.data.message);
                        setData(null);
                        setIsLoading(false);
                    });
            }
        } catch (err) {
            
        } finally {
            setIsLoading(false);
        }
    }

    return [data, isLoading, error, fetchData];
}

export default useAxios;